package cc.lirns.demo.websocket.withspring.config;

import cc.lirns.demo.websocket.withspring.handler.MyWsHandle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * 启用spring整合的websocket
 *
 * @author liruilin
 * @date 2021/10/8 15:04
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final MyWsHandle myWsHandle;

    public WebSocketConfig(MyWsHandle myWsHandle) {
        this.myWsHandle = myWsHandle;
    }

    /**
     * 该bean是用于解决冲突的
     * 启用该websocket配置后会和系统中的定时器发生冲突 需要使用如下方式解决
     *
     * @return taskScheduler
     */
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);
        taskScheduler.initialize();
        return taskScheduler;
    }

    /**
     * 将消息处理器和对应路径结合起来并设置允许的作用域
     *
     * @param registry 注册用的
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册自定义消息处理，消息路径为`/ws/foo`
        registry.addHandler(myWsHandle, "/myWsHandle").setAllowedOrigins("*");
    }
}
